<?php

namespace app\common\model;

use think\Model;

class Orderinviter extends Model {

    /**
     * 判断是否为首单
     */
    public function isFirstOrder($member_id) {
        return !db('exppointslog')->where([
            'explog_memberid' => $member_id,
            'explog_stage' => 'order'
        ])->find();
    }

    /**
     * 添加积分记录
     */
    public function addOrderInviter($order, $inviter_id, $inviter_type) {
        // 是否为会员
        $inviter = Member::get([
            'member_id' => $inviter_id,
            'member_type' => $inviter_type
        ]);
        if(!$inviter) return;

        // 虚拟订单
        if(isset($order['vr_indate'])) {
            $vr = 1;
            $order['goods_amount'] = $order['goods_num'] * $order['goods_price'];
            $goods = [$order];
        } else {
            $vr = 0;
            $goods = $order['extend_order_goods'];
        }

        if($inviter_type == MEMBER_TYPE_3) {
            // 会员推荐
            $points = config('inviter_points');
            $msg = '获得推荐积分：'.$points.' 点，订单号：' . $order['order_sn'];
            $msg2 = '获得推荐积分：'.$points.' 点';
        } else {
            $inviter_inviter = Inviter::get($inviter_id);

            // 判断是否开启
            if($inviter_inviter['inviter_state'] != INVITER_STATE_PASS) return;
            // 门店统计
            $points = $order['goods_amount'] * $inviter_inviter['inviter_ratio'] * 0.01;
            $msg = '获得门店销售积分：'.$points.' 点，订单号：' . $order['order_sn'];
            $msg2 = '获得门店销售积分：'.$points.' 点';
        }

        $inviter_info = Inviter::get($inviter_id);
        // 添加积分记录
        $data = array(
            'orderinviter_order_time' => $order['add_time'],
            'orderinviter_addtime' => TIMESTAMP,
            'orderinviter_goods_amount' => $order['goods_amount'],
            'orderinviter_goods_quantity' => array_sum(array_column($goods, 'goods_num')),
            'orderinviter_type' => $inviter_type,
            'orderinviter_order_type' => $vr,
            'orderinviter_order_id' => $order['order_id'],
            'orderinviter_order_sn' => $order['order_sn'],
            'orderinviter_member_id' => $inviter['member_id'],
            'orderinviter_member_name' => $inviter_type == MEMBER_TYPE_3 ? $inviter['member_name'] : $inviter_info['inviter_name'],
            'orderinviter_points' => $points,
            'orderinviter_remark' => $msg,
            'orderinviter_valid' => 1,
        );

        isset($order['store_id']) and $data['orderinviter_store_id'] = $order['store_id'];
        isset($order['store_name']) and $data['orderinviter_store_name'] = $order['store_name'];

        $this->insert($data);

        $inviter_model = model('inviter');
        // 积分变更
        $change_data = array();
        $change_data['member_id'] = $data['orderinviter_member_id'];
        $change_data['member_name'] = $data['orderinviter_member_name'];
        $change_data['member_type'] = $data['orderinviter_type'];
        $change_data['points'] = $points;
        $change_data['order_sn'] = $data['orderinviter_order_sn'];
        $change_data['lg_desc'] = $msg;
        $inviter_model->changePoints($inviter_type, 'order_inviter', $change_data);

        if($inviter_type == MEMBER_TYPE_3) return;

        // 销量统计
        foreach($goods as $item) {
            $goods_item = Goods::get($item['goods_id']);
            if($goods_item) {
                db('goodscommon')->where('goods_commonid=' . $goods_item['goods_commonid'])->setInc('inviter_total_quantity', $item['goods_num']);
                db('goodscommon')->where('goods_commonid=' . $goods_item['goods_commonid'])->setInc('inviter_total_amount', $item['goods_num'] * $item['goods_price']);
            }
        }

        // 店铺销量统计
        db('inviter')->where('inviter_id=' . $inviter_id)->setInc('inviter_order_quantity', 1);
        db('inviter')->where('inviter_id=' . $inviter_id)->setInc('inviter_order_amount', $order['order_amount']);
        db('inviter')->where('inviter_id=' . $inviter_id)->setInc('inviter_goods_quantity', $data['orderinviter_goods_quantity']);
        db('inviter')->where('inviter_id=' . $inviter_id)->setInc('inviter_goods_amount', $data['orderinviter_goods_amount']);

        if($inviter_type == MEMBER_TYPE_2) {
            $order['store_id'] = $inviter_id;
            $order['store_name'] = $inviter_info['inviter_name'];
            // agent
            $inviter = Member::parentInviter($inviter);
            $this->addOrderInviter($order, $inviter['member_id'], MEMBER_TYPE_1);
        }
    }

    /**
     * 支付给钱
     * @access public
     * @author yunku
     * @param type $order_id 订单编号
     * @param bool $vr  是否为虚拟订单
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function givePoints($order_id, $vr = false) {
        $inviter_model = model('inviter');
        try {
            $inviter_model->startTrans();

            // 查询支付订单
            if($vr) {
                $order = (new Vrorder())->getVrorderInfo([
                    'order_id' => $order_id
                ], ['member', 'order_goods']);
            } else {
                $order = (new Order())->getOrderInfo([
                    'order_id' => $order_id
                ], ['member', 'order_goods']);
            }

            // 判断是否为首单
            $member = $order['extend_member'];

            $is_first_order = $this->isFirstOrder($member['member_id']);

            // 首单推荐人拿积分
            if ($is_first_order) {
                $this->addOrderInviter($order, $member['inviter_id'], MEMBER_TYPE_3);
            }
            // 添加分店积分统计
            $this->addOrderInviter($order, $member['store_id'], MEMBER_TYPE_2);

            $inviter_model->commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            echo $e->getTraceAsString();
            $inviter_model->rollback();
            throw $e;
        }
    }

}
